<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="证券代码" prop="stockCode">
        <el-input
            v-model="queryParams.stockCode"
            placeholder="请输入证券代码"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账号标签" prop="accountTag">
        <el-select v-model="queryParams.accountTag" placeholder="请选择股票账号标签" clearable style="width: 240px">
          <el-option
              v-for="dict in stock_account_tag"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              :data="statStockList"
              show-summary
              :summary-method="getSummaries">
      <el-table-column label="账号标签" align="center" prop="accountTag">
        <template #default="scope">
          <dict-tag :options="stock_account_tag" :value="scope.row.accountTag"/>
        </template>
      </el-table-column>

      <el-table-column label="证券代码" align="center" prop="stockCode"/>
      <el-table-column label="证券名称" align="center" prop="stockName"/>
      <el-table-column label="买入总股数" align="center" prop="totalBuyQuantity"/>
      <el-table-column label="卖出总股数" align="center" prop="totalSellQuantity"/>
      <!--      <el-table-column label="买入均价" align="center" prop="averageBuyPrice">-->
      <!--        <template #default="scope">-->
      <!--          {{ (scope.row.totalBuyAmount / scope.row.totalBuyQuantity || 0).toFixed(2) }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="买入总金额" align="center" prop="totalBuyAmount"/>
      <el-table-column label="卖出总金额" align="center" prop="totalSellAmount"/>
      <!--      <el-table-column label="卖出均价" align="center" prop="averageSellPrice">-->
      <!--        <template #default="scope">-->
      <!--          {{ Math.abs((scope.row.totalSellAmount / scope.row.totalSellQuantity || 0).toFixed(2)) }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="盈亏" align="center" prop="profit"/>
      <el-table-column label="收益率" align="center" prop="profitRatio">
        <template #default="scope">
          {{ (scope.row.profit / -scope.row.totalBuyAmount * 100).toFixed(2) }}%
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="170px">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleViewDetails(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100, 200,500]"
        @pagination="getList"
    />

    <!-- 交易详情弹窗 -->
    <el-dialog title="交易详情" v-model="detailDialogVisible" width="80%" top="5vh">
      <el-table :data="tradeDetails"
                v-loading="detailLoading"
                max-height="800px"
                show-summary
                :summary-method="getDialogSummaries">
        <el-table-column label="成交日期" align="center" prop="tradeDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.tradeDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属账号" align="center" prop="accountNo">
          <template #default="scope">
            {{ getAccountName(scope.row.accountNo) }}
          </template>
        </el-table-column>
        <el-table-column label="证券代码" align="center" prop="stockCode"/>
        <el-table-column label="证券名称" align="center" prop="stockName"/>
        <el-table-column label="操作" align="center" prop="operation"/>
        <el-table-column label="交易股数" align="center" prop="tradeQuantity"/>
        <el-table-column label="均价" align="center" prop="averagePrice"/>
        <el-table-column label="交易金额" align="center" prop="tradeAmount"/>
        <el-table-column label="总费用" align="center" prop="totalFees"/>
        <el-table-column label="发生金额" align="center" prop="occurredAmount"/>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {listStatStock,} from "@/api/stock/stat_stock";
import {formatCurrency} from "@/utils/format.js";
import {listAccount} from "@/api/stock/account";
import {listStatSettlement} from "@/api/stock/settlement"

const {proxy} = getCurrentInstance();
const {stock_account_tag} = proxy.useDict('stock_account_tag');

const statStockList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

// 详情弹窗相关
const detailDialogVisible = ref(false);
const detailLoading = ref(false);
const tradeDetails = ref([]);
const accountOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stockCode: null,
    accountTag: null,
    zero: 'True',
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

const getSummaries = (param) => {
  const {columns, data} = param
  const sums = []

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '统计'
    }
    if (index === 1) {
      sums[index] = '共' + data.length + '条'
    }
    if (column.property === 'totalBuyQuantity') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }
    if (column.property === 'totalSellQuantity') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }
    if (column.property === 'totalBuyAmount') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }
    if (column.property === 'totalSellAmount') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }
    if (column.property === 'profit') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }
  })

  return sums
}

const getDialogSummaries = (param) => {
  const {columns, data} = param
  const sums = []

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '统计'
    }
    if (index === 1) {
      sums[index] = '共' + data.length + '条'
    }
    if (column.property === 'tradeQuantity') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }
    if (column.property === 'totalFees') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }
    if (column.property === 'occurredAmount') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }

  })

  return sums
}

/** 查询股票统计列表 */
function getList() {
  loading.value = true;
  listStatStock(queryParams.value).then(response => {
    statStockList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 查看详情 */
function handleViewDetails(row) {
  detailLoading.value = true;
  detailDialogVisible.value = true;
  tradeDetails.value = [];

  listStatSettlement(row.stockCode, row.accountTag).then(response => {
    tradeDetails.value = response.rows;
    detailLoading.value = false;
  }).catch(() => {
    detailLoading.value = false;
    proxy.$modal.msgError("获取交易详情失败");
  });
}

/** 获取账户列表 */
function getAccountList() {
  listAccount({}).then(response => {
    accountOptions.value = response.rows;
  });
}

/** 获取账户名称 */
function getAccountName(accountNo) {
  if (!accountNo) return '';
  const account = accountOptions.value.find(item => item.accountNo === accountNo);
  return account ? account.accountName : accountNo;
}

Promise.all([getList(), getAccountList()]);
</script>
